<?php
namespace LnkAdmin\support;


class SqlExecute
{
    // mysqli连接对象
    private $connect = null;
    // mysql配置
    private $mysqlInfo = [];

    public function __construct($mysqlInfo = [])
    {
        
        if(empty($mysqlInfo)){
            $this->mysqlInfo = config('database.connections.mysql');
          
        }else{
            $this->mysqlInfo = $mysqlInfo;
        }
        
        $this->connect = @mysqli_connect($this->mysqlInfo['hostname'] . ':' . $this->mysqlInfo['hostport'], $this->mysqlInfo['username'], $this->mysqlInfo['password']);
        mysqli_select_db($this->connect, $this->mysqlInfo['database']);
    }

    /**
     * 执行isntall.sql
     */
    public  function execInstallSql($plugin)
    {
        if($plugin == 'admin'){
            $mysqlPath = __DIR__.'/../install/' . 'install.sql';
        }else{
            $mysqlPath = root_path("app/{$plugin}/install") . 'install.sql';
        }
       
        $sqlRecords = file_get_contents($mysqlPath);
        $sqlRecords = str_ireplace("\r", "\n", $sqlRecords);

        // 替换数据库表前缀
        $sqlRecords = explode(";\n", $sqlRecords);
        $sqlRecords = str_replace(" `__PREFIX__", " `{$this->mysqlInfo['prefix']}", $sqlRecords);

        
        $this->execSql($sqlRecords);

        return true;
    }

    /**
     * 执行data.sql
     */
    public function execDataSql($plugin,$getVer=0)
    {
        if($plugin == 'admin'){
            $mysqlPath = __DIR__.'/../install/' . 'data.sql';
        }else{
            $mysqlPath = root_path("app/{$plugin}/install") . 'data.sql';
        }
        
        $sqlRecords = file_get_contents($mysqlPath);
        $sqlRecords = str_replace(";\r\n", ";\n", $sqlRecords);
        $sqlRecords = str_replace(" `__PREFIX__", " `{$this->mysqlInfo['prefix']}", $sqlRecords);
		$vers = array();
		$curVer = 0;
		foreach (explode("\n", $sqlRecords) as $row) {
			$row = trim($row);
			preg_match_all('/^--\s*\[v(\d+)\]/', $row, $matches);
            // var_dump($matches);
			if ($matches && $matches[1]) {
				$curVer = $matches[1][0];
				$vers[$curVer] = '';
			} elseif ($curVer > 0) {
				$vers[$curVer] .= $row . "\n";
			}
           
		}
        // var_dump($vers);
		$return = [];
		foreach ($vers as $ver => $sql) {
			if ($getVer < $ver) { 
                $return = array_merge($return,explode("\n",$sql));
			}
		}
        $this->execSql($return);
        // var_dump($return);
		return [$return, $curVer];

        
    }

    /**
     * 执行sql
     */
    private function execSql(array $sqlRecords)
    {
        mysqli_query($this->connect, "set names utf8mb4");
        foreach ($sqlRecords as $index => $sqlLine) {
            $sqlLine = trim($sqlLine);
            if (!empty($sqlLine)) {
                try {
                    // 创建表数据
                    if (mysqli_query($this->connect, $sqlLine) === false) {
                        throw new \Exception(mysqli_error($this->connect));
                    }
                } catch (\Throwable $th) {
                    return error($th->getMessage());
                }
            }
        }

        return true;
    }
}